package com.management.department.teacherinfosystem.Controller;

import com.management.department.teacherinfosystem.Entity.User;
import com.management.department.teacherinfosystem.Entity.VolunteerService;
import com.management.department.teacherinfosystem.Repository.UserRepository;
import com.management.department.teacherinfosystem.Repository.VolunteerServiceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/volunteer")
@CrossOrigin(origins = "*")
public class VolunteerServiceController {
	@Autowired private VolunteerServiceRepository repository;
	@Autowired private UserRepository userRepository;

	@PostMapping
	@Transactional
	public ResponseEntity<?> create(@RequestBody Map<String,Object> payload) {
		User current = currentUser();
		if (current == null) return ResponseEntity.status(401).body("未登录");
		VolunteerService v = new VolunteerService();
		v.setUserId(current.getId());
		v.setServiceTitle((String) payload.get("service_title"));
		v.setServiceType((String) payload.get("service_type"));
		v.setServiceDate(parseDate(payload.get("service_date")));
		v.setServiceHours(asDouble(payload.get("service_hours")));
		v.setLocation((String) payload.get("location"));
		v.setDescription((String) payload.get("description"));
		repository.save(v);
		return ResponseEntity.ok(Map.of("id", v.getId()));
	}

	@GetMapping("/mine")
	@Transactional(readOnly = true)
	public ResponseEntity<?> mine() {
		User current = currentUser();
		if (current == null) return ResponseEntity.status(401).body("未登录");
		return ResponseEntity.ok(repository.findByUserId(current.getId()));
	}

	@PutMapping("/{id}")
	@Transactional
	public ResponseEntity<?> update(@PathVariable("id") Long id, @RequestBody Map<String,Object> payload) {
		VolunteerService v = repository.findById(id).orElse(null);
		if (v == null) return ResponseEntity.notFound().build();
		User current = currentUser();
		if (current == null || !Objects.equals(v.getUserId(), current.getId())) return ResponseEntity.status(403).body("无权修改");
		v.setServiceTitle((String) payload.getOrDefault("service_title", v.getServiceTitle()));
		v.setServiceType((String) payload.getOrDefault("service_type", v.getServiceType()));
		Date d = parseDate(payload.get("service_date")); if (d != null) v.setServiceDate(d);
		Double h = asDouble(payload.get("service_hours")); if (h != null) v.setServiceHours(h);
		v.setLocation((String) payload.getOrDefault("location", v.getLocation()));
		v.setDescription((String) payload.getOrDefault("description", v.getDescription()));
        // 教职工修改后回到待审核
        v.setStatus("PENDING");
		repository.save(v);
		return ResponseEntity.ok().build();
	}

	@DeleteMapping("/{id}")
	@Transactional
	public ResponseEntity<?> delete(@PathVariable("id") Long id) {
		VolunteerService v = repository.findById(id).orElse(null);
		if (v == null) return ResponseEntity.notFound().build();
		User current = currentUser();
		if (current == null || !Objects.equals(v.getUserId(), current.getId())) return ResponseEntity.status(403).body("无权删除");
		repository.deleteById(id);
		return ResponseEntity.ok().build();
	}

	// admin
	@GetMapping("/all")
	@Transactional(readOnly = true)
	public ResponseEntity<?> all(@RequestParam(value = "status", required = false) String status,
	                             @RequestParam(value = "startDate", required = false) String startDate,
	                             @RequestParam(value = "endDate", required = false) String endDate) {
		User current = currentUser();
		if (current == null) return ResponseEntity.status(401).body("未登录");
		boolean isAdmin = current.getUserRoles().stream().anyMatch(ur -> ur.getRole() != null && "admin".equalsIgnoreCase(ur.getRole().getName()));
		if (!isAdmin) return ResponseEntity.status(403).body("权限不足");
		List<VolunteerService> list;
		if (status != null && !status.isBlank()) list = repository.findByStatus(status);
		else list = repository.findByDateRange(parseDate(startDate), parseDate(endDate));
		return ResponseEntity.ok(list);
	}

	@PostMapping("/{id}/review")
	@Transactional
	public ResponseEntity<?> review(@PathVariable("id") Long id, @RequestBody Map<String,Object> payload) {
		User current = currentUser();
		if (current == null) return ResponseEntity.status(401).body("未登录");
		boolean isAdmin = current.getUserRoles().stream().anyMatch(ur -> ur.getRole() != null && "admin".equalsIgnoreCase(ur.getRole().getName()));
		if (!isAdmin) return ResponseEntity.status(403).body("权限不足");
		VolunteerService v = repository.findById(id).orElse(null);
		if (v == null) return ResponseEntity.notFound().build();
		String status = (String) payload.get("status");
		if (!"APPROVED".equals(status) && !"REJECTED".equals(status)) return ResponseEntity.badRequest().body("状态无效");
		v.setStatus(status);
		repository.save(v);
		return ResponseEntity.ok().build();
	}

	private Date parseDate(Object value) { if (value==null) return null; try { return new SimpleDateFormat("yyyy-MM-dd").parse(String.valueOf(value)); } catch(Exception e){ return null; } }
	private Double asDouble(Object v) { return v==null?null:Double.valueOf(String.valueOf(v)); }
	private User currentUser() {
		org.springframework.security.core.Authentication auth =
				org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
		String currentUsername = auth == null ? null : auth.getName();
		return currentUsername == null ? null : userRepository.findByUsernameWithRoles(currentUsername).orElse(null);
	}
} 